﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using SisCRA.Config;

namespace SisCRA.Database
{
    public class Connection
    {
        #region -Private Attributes-

        private static Connection instance;

        private string connectionString;
        private MySqlConnection conn;

        #endregion

        #region -Public Properties-

        /// <summary>
        /// String de conexão com o banco de dados.
        /// </summary>
        public string ConnectionString
        {
            get { return connectionString; }
            set { connectionString = value; }
        }

        /// <summary>
        /// Objeto de conexão com o banco de dados.
        /// </summary>
        public MySqlConnection Conn
        {
            get { return conn; }
            set { conn = value; }
        }

        #endregion

        #region -Constructor-

        /// <summary>
        /// Construtor padrão.
        /// Cria um objeto de conexão com o banco de dados a partir das informações obtidas do arquivo de configuração SisCRA.config.
        /// </summary>
        private Connection()
        {
            try
            {
                connectionString = AppConfig.Server + "=" + AppConfig.ReadConfiguration(AppConfig.Server) + ";" +
                                   AppConfig.User + "=" + AppConfig.ReadConfiguration(AppConfig.User) + ";" +
                                   AppConfig.Password + "=" + AppConfig.ReadConfiguration(AppConfig.Password) + ";" +
                                   AppConfig.Database + "=" + AppConfig.ReadConfiguration(AppConfig.Database) + ";" +
                                   AppConfig.Port + "=" + AppConfig.ReadConfiguration(AppConfig.Port) + ";";

                conn = new MySqlConnection(connectionString);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region -Singleton-

        /// <summary>
        /// Retorna uma instância da classe Connection.
        /// </summary>
        public static Connection Instance
        {
            get 
            {
                if (instance == null || instance.conn == null)
                {
                    instance = new Connection();
                }

                return instance;
            }
        }

        #endregion

        #region -Public Methods-

        /// <summary>
        /// Destrói a instância atual da classe Connection.
        /// </summary>
        public void DestroyConnection()
        {
            if (instance != null)
            {
                instance.connectionString = string.Empty;
                instance.conn = null;
            }
        }

        #endregion
    }
}
